// to avoid pb this file is JSLint campatible http://www.jslint.com/

var myChatFrame; //pointer to the chat frame. Use to drag it (to have it persistent).
var dragData = null;// drag data (to have it persistent).
var myUserName = "";// my user name as soon as I know it
var myChatroom ="";
/// when a user reloads the page,ihe leaves the room and re-enters so that if we do nothing, message will be loged in the chat.
/// When a user log out we wait 10sec before displaying the message and abort if he has loged back in in between.
/// thefollowing variables allow for that
var myLeaveAndEnterRoomStr = "";
var myLeaveAndEnterRoomNick = "";
var myLeaveAndEnterRoomDate = "";

//-----------------------------------------------------------------------------------
// log the messages with the date
function log(msg, date, speaker) {
    var tmp = '--------------------- ' + date + ', ' + speaker + ' says:';
    $('#notifications').append('<div>' + tmp + '</div>');
    $('#notifications').append('<div>' + msg + '</div>');
    my_notificationBox = document.getElementById('notifcationBox');   
    my_notificationBox.scrollTop = my_notificationBox.scrollHeight;
    return false;
}

//--------------------------------------------------------------------------------------
// return the curent date as string
function getDateString() {
    var today = new Date();
    var dd = today.getDate();
    if (dd < 10) {
        dd = '0' + dd;
    }
    var mm = today.getMonth() + 1;//January is 0!
    if (mm < 10) {
        mm =  '0' + mm;
    } 
    var mins = today.getMinutes();
    if (mins < 10) {
        mins =  '0' + mins;
    }
    var secs = today.getSeconds();
    if (secs < 10) {
        secs =  '0' + secs;
    }
    var year = today.getFullYear();
    return year+ '-' + mm + '-' + dd + '   ' + today.getHours() + ':' + mins + ':' + secs;
}


//--------------------------------------------------------------------------------------
// display the message in the notification box
function notifyUserMsg(msg) {
    var msg_js = $(msg);
    var msgTxt = msg_js.children('body').text();
    var fromAll = msg_js.attr('from');
    var nick = 'betroom';
    
    var reloadJson = false;
    if ( fromAll.indexOf( '_web' ) != -1 ) {
        var ressource = fromAll.substring(fromAll.indexOf("/"), fromAll.length);
        nick = ressource.substring(1, ressource.indexOf("_"));
    }
    else {
        /// when te betroom is speaking we want to reload the json when somebody else has taken an action.
        /// we considere that if the user is the one who has just taken the action, the message will begin with his name
        if( msgTxt.substr(0,myUserName.length) != myUserName ){//it is another user taking an action
            reloadJson = true;
        }
    }
 
    var indexOfSlash = fromAll.indexOf('/');
    var from = fromAll.substring(indexOfSlash + 1, fromAll.length);
    var dateStr = "";
    try {
        var delay = msg_js.children('delay');
        dateStr = delay.attr('stamp');
        dateStr = dateStr.replace("T","  "); 
        dateStr = dateStr.replace("Z",""); 
    }
    catch (e) {
        dateStr = getDateString();
    }
    dateStr = getDateString();
    log( msgTxt, dateStr, nick );
    // Reading the documentation in http://code.stanziq.com/strophe/strophejs/doc/1.0.1/files/core-js.html#Strophe.Connection.addHandler i
    // found this line :
    //The handler should return true if it is to be invoked again; returning false will remove the handler after it returns.
    if( reloadJson ) {
        callJsonsFromPythonThenApplyJSFuncToThem();
    }
	return true;
}

//--------------------------------------------------------------------------------------
// log a message for a user having left the room when he has not loged back in between
function delayed_log_for_room_left() {
    if( myLeaveAndEnterRoomStr == myLeaveAndEnterRoomNick.toLowerCase()+'has_left_recently' ) {
        log(myLeaveAndEnterRoomNick + ' has left the bet room', myLeaveAndEnterRoomDate, 'betroom');
        myLeaveAndEnterRoomStr ='';
    }
}
function clearLeaveAndEnterRoomStr() {
   myLeaveAndEnterRoomStr ="";
}


//--------------------------------------------------------------------------------------
// handle a presence tag the message in the notification box
function notifyUserPres(presence) {

    var from = $(presence).attr('from'); // the jabber_id of the contact
    var ressource = from.substring(from.indexOf("/"), from.length);
    var nick = ressource.substring(1, ressource.indexOf("_"));
    //print the nick if it is different from /, celibax and the user name 
    var printNick = (nick.length > 1);
    if (printNick)
    {
        printNick = nick.substring(0, 1) !=  '/'
        printNick = printNick && (nick.toLowerCase() !=  'celibax');
        printNick = printNick && (nick.toLowerCase() !=  myUserName.toLowerCase());
    }
    var presence_type = $(presence).attr('type'); // unavailable, subscribed, etc...
    if (presence_type ==  'error')
    {
        log('An error occured, please reload the page for further notifications', getDateString(), 'betroom');
    }
    else {
        // there is no type: signal as online (but only for the player and not for 'celibax' (the python bot))
        if (printNick) {
            if (typeof(presence_type) == 'undefined') {
                // if the user has not just left the room, log him as entering
                if( myLeaveAndEnterRoomStr != nick.toLowerCase()+'has_left_recently' ) {
                    if( myLeaveAndEnterRoomStr != nick.toLowerCase()+'has_joined_recently' ) {
                        log(nick + ' has joined the bet room', getDateString(), 'betroom');
                        myLeaveAndEnterRoomStr = nick.toLowerCase()+'has_joined_recently';
                    }
                }
                myLeaveAndEnterRoomStr = nick.toLowerCase()+'has_joined_recently';
                setTimeout('clearLeaveAndEnterRoomStr()',3000);
            }
            else {
                // when the user reloads the page, he leaves the room and re-enters, we do not want to show the message
                // Mark contact as offline
                myLeaveAndEnterRoomStr = nick.toLowerCase()+'has_left_recently';
                myLeaveAndEnterRoomNick = nick;
                myLeaveAndEnterRoomDate = getDateString();
                setTimeout('delayed_log_for_room_left()',3000);
            }    
        }
    }

    // Reading the documentation in http://code.stanziq.com/strophe/strophejs/doc/1.0.1/files/core-js.html#Strophe.Connection.addHandler i
    // found this line :
    //The handler should return true if it is to be invoked again; returning false will remove the handler after it returns.
    return true;
}


//--------------------------------------------------------------------------------------
// handle a presence tag the message in the notification box
function sendMessage()
{
    Candy.Core.Action.Jabber.Room.Message( myChatroom, $('#id_msgBox').val(), "groupchat");
    $('#id_msgBox').val( "" );
    return true;
}

//--------------------------------------------------------------------------------------
// attacgh to chat connection
function attachToChatConnection() { 
	var args = { 
           type: 'POST', 
           url: '/manageChatConnection/',
           cache: false,
           complete:function(res) {         
                        var resAsTxt = eval(res.responseText);
                        if (resAsTxt.toString().substr(0,5) ==  "error") { 
                            $('#id_Notifications').text('Notifications');
                            log(resAsTxt, getDateString(), 'sytem');
                        }
                        myUserName = resAsTxt[0].playerName;
                        var ressource = myUserName+ '_' +resAsTxt[0].betroomName+ '_web';
                        myChatroom = resAsTxt[0].chatRoomName+resAsTxt[0].chatRoomExtension;
                        Candy.init(
                            resAsTxt[0].BOSH_SERVICE, 
                            {   
                                 core: { debug: false, autojoin: [ myChatroom+"/"+ressource ] },
                                 view: { resources: '../candy/res/' } 
                            }
                        );
                        Candy.Core.attach(resAsTxt[0].jid,  resAsTxt[0].sid, resAsTxt[0].rid + 1);
                        Candy.Core.addHandler(notifyUserMsg, null, 'message', null, null, null);
                        Candy.Core.addHandler(notifyUserPres, null, 'presence', null, null, null);
                        $('#id_Notifications').text('Notifications');
                        if( resAsTxt[0].speakingAllowed )
                        {   
                            var textAreaStr = '<textarea id="id_msgBox" rows="2" cols="36" onkeypress="ifEnter(this,event,sendMessage);"/>';
                            $('#id_chatFrame').append( textAreaStr );
                        }
                        return true;
                    },
           error: function(errorThrown) { $('#id_Notifications').text('Notifications'); log(errorThrown, getDateString(), 'system');  }
           };
      chatConnectionRequest = $.ajax(args);
      return true; 
 }
 
//--------------------------------------------------------------------------------------
// register the position at the beginning of the drag
function startDrag(ev) {
  if (!dragData) {
    ev = ev||event;
    dragData = { x: ev.clientX-myChatFrame.offsetLeft, y: ev.clientY-myChatFrame.offsetTop };
  }
  return true; 
}

//--------------------------------------------------------------------------------------
// change the position of the chat frame
function drag(ev)
{
  if (dragData) {
    ev = ev||event;
    myChatFrame.style.left = ev.clientX-dragData.x + "px";
    myChatFrame.style.top = ev.clientY-dragData.y + "px";
  }
  return true; 
}

//--------------------------------------------------------------------------------------
// release the drag data
function stopDrag(ev)
{
  if (dragData) {
    ev = ev||event;
    myChatFrame.style.left = ev.clientX-dragData.x + "px";
    myChatFrame.style.top = ev.clientY-dragData.y + "px";
    dragData = null;
  }
  return true; 
}
//--------------------------------------------------------------------------------------
// create the chatwindow
function create_chat_box() {
    /* the structure is the following:
    the chatFrame is the window that contains all the chat information, it contains:
        - the chat header (a blue line on top), it contains
            - one of the 2 chatWindowResizer wich are button to resize the chatFram. When the chat fram is extended, 
              it contains the chatWindowResizer to minimise. When the chat frame is minimised, it contains the
              chatWindowResizer to extend.
        - the chat body which is the fram for all the data, for now it contains only the box where the messages are displayed
          but it could contains, the online user information, a "send" section", .... It contains:
            - a notification box where the messages are displayd.
    */

    var str = '';
    str += '<div class = "chatFrame" id = "id_chatFrame">';
    str += '    <div class = "chatHeader" id = "id_chatHeader">';
    str += '        <div id = "id_Notifications" >Notifications (connecting...)</div>';
    str += '        <div class = "chatWindowResizer chatWindowCloser" id = "id_chatWindowCloser" onclick = "changeChatSize(false)">-</div>';
    str += '        <div class = "chatWindowResizer chatWindowOpener"  id = "id_chatWindowOpener" onclick = "changeChatSize(true)">&#9794;</div>';
    str += '    </div>';
    str += '    <div class = "chatBody" id = "id_chatBody">';
    str += '        <div id = "notifcationBox">';
    str += '            <div id = "notifications">';
    str += '        </div>';
    str += '    </div>';
    str += '</div>';
    $('body').append(str);
    
    
    //declare the body as a listener so that we will be able to drag
    myChatFrame = document.getElementById("id_chatFrame");
    $('#id_chatHeader').mousedown(startDrag);
	$('body').mousemove(drag);
	$('body').mouseup(stopDrag);
	var match = navigator.userAgent.match('MSIE (.)');
    var version = match && match.length > 1 ? match[1] : 'unknown';
    if( version == '5' || version == '6' || version == '7' || version == '8' || version == '9' )
    {
        $('#id_Notifications').text('Notifications');
        log('The notifications are not suported with internet explorer with a version lower than 10.', getDateString(), 'betroom');
           
    }
    else
    {
        attachToChatConnection();
    }
    attachCSS3Properties();
    return true;
 }


//--------------------------------------------------------------------------------------------------------------------
// sets the specified style string for the specified object according to the web browser
function setStyleAttribute( elmtObject, styleString)
{
    var name = navigator.appName;
    // firefox returns Netscape
    //var ns = (name == 'Netscape') ? 1:0; 
    var ie = (name == 'Microsoft Internet Explorer') ? 1:0;
    if( ie )
    {
        elmtObject.style.setAttribute('cssText',styleString );
    }
    else
    {
        elmtObject.setAttribute('style',styleString );
    }
    return false;
};

//--------------------------------------------------------------------------------------
//  change the size of the chat window
function changeChatSize(makeItLarge) {
    var frame = document.getElementById('id_chatFrame');
    var header = document.getElementById('id_chatHeader');
    var body = document.getElementById('id_chatBody');
    if (makeItLarge) {
        $('#id_chatWindowOpener').css('display', 'none');
        $('#id_chatWindowCloser').css('display', 'inline');
        setStyleAttribute(frame,'height: auto;');
        setStyleAttribute(header,'height: 3%;');
        setStyleAttribute(body,'height: 96%;');
        $('#id_msgBox').css('display', 'inline');
    }
    else{
        $('#id_chatWindowOpener').css('display', 'inline');
        $('#id_chatWindowCloser').css('display', 'none');
        $('#id_chatBody').css('display', 'none');
        $('#id_msgBox').css('display', 'none');
        setStyleAttribute(frame,'height: 20px;');
        setStyleAttribute(header,'height: 99%;');
    }
    return true;    
}
